<?php include_once 'ra_global1.php';
define("TOKEN", "rams1234");
define("SELLSCORE", 15);


$wechatObj = new wechatCallbackapiTest();
//$wechatObj->valid();
$wechatObj->responseMsg($db);

class wechatCallbackapiTest{
	public function valid(){
		$echoStr = $_GET["echostr"];
		//valid signature , option
		if($this->checkSignature()){
			echo $echoStr;
			exit;
		}
	}

	public function responseMsg($db){
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		
	  	//extract post data
		if (!empty($postStr)){
			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			$this->fromUsername = $postObj->FromUserName;
			$this->toUsername = $postObj->ToUserName;
			$ticket = $postObj->Ticket;
			$event = $postObj->Event;
			$eventKey = trim($postObj->EventKey);
			$MsgType=trim($postObj->MsgType);
			$url='http://rams.cc/m/shellexpert/reg.php';
			$picurl='http://rams.cc/m/shellexpert/shopcode/90001.jpg';
			$des='';
			if($MsgType=='event'){
				//事件处理
				switch($event){
					case 'scancode_waitmsg':
						//自定义菜单扫描等待消息
						if($eventKey === 'scanoil'){
							//扫码验证
							$user=$db->ig2_want('mae_user','role_type=2 and openid="'.$this->fromUsername.'"');
							if(!$user){
								//扫描人不是店员
								$this->sendTxt('只有店员可以验证');
							}
							$role=$db->ig2_want('mae_role','is_delete=0 and uid='.$user['id']);
							$ScanResult=$postObj->ScanCodeInfo->ScanResult;
							$ScanResult=explode('?',$ScanResult);
							if(sizeof($ScanResult)==2){
								$ScanResult=$ScanResult[1];
								$ScanResult=substr($ScanResult,1,16);
								if(is_numeric($ScanResult) && strlen($ScanResult)==16){
									//正常获得16位数字产品编码
									$client = new SoapClient("http://accode.zhsh.co/CcnOutService.asmx?WSDL");
									$param = array(
										'userID'=>'02LS9JJ1ZQQCBVN73K392J999293K1',
										'userPwd'=>'5A82D28LAO20K38IKMNBU28KE8DD',
										'ip'=>$this->GetIP(),
										'acCode'=>$ScanResult,
										'language'=>'zh-cn',
										'channel'=>'21'
									);
									$p = $client->__soapCall('Get_ACCodeProductInfo',array('parameters' => $param));
									$state=$p->systemState;
									$state=substr($state,0,4);
									switch($state){
										case '1002':
											//数码存在
											$sell=$db->ig2_want('mae_sell','shell_key="'.$ScanResult.'"');
											if($sell){
												//已售出
												$this->sendTxt('此商品已售出');
											}else{
												//未售出
												$reply=$p->reply;
												$reply = simplexml_load_string($reply, 'SimpleXMLElement', LIBXML_NOCDATA);
												if($reply->item->productid=='' && ($reply->item->productspec=='小桶(3.5L-5L)'||$reply->item->productspec=='1L-5L'||$reply->item->productspec=='4L')){
													$reply->item->productid=550000000;
												}
												$pro=$db->ig2_want('mae_pro','pro_id="'.$reply->item->productid.'"');
												$p->reply=$reply;
												$p=json_encode($p);
												if($pro){
													//是活动商品
													$co=0;
													$succes=false;
													while(!$succes){
														$succes=true;
														$id=rand(1,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9);
														$db->ig2_query('BEGIN');
														//插入销售记录
														$result1=$db->ig2_query("insert into mae_sell (`id`,`account_id`,`shell_key`,`pro_id`,`productname`,`productspec`,`productinfo`,`uid`,`create_time`) values ('".$id."','16621','".$ScanResult."','".$reply->item->productid."','".$reply->item->productname."','".$reply->item->productspec."','".$p."','".$user['id']."','".time()."');");
														$succes=$succes && $result1?true:false;
														//更新积分
														$result2=$db->ig2_query("update mae_user set score=".($user['score']+SELLSCORE)." WHERE id=".$user['id']);
														$succes=$succes && $result2?true:false;
														$result3=$db->ig2_query("update mae_shop set sell_count=sell_count+1,now_month_count=now_month_count+1,quadratic=quadratic+".SELLSCORE." WHERE id=".$role['shop_id']);
														$succes=$succes && $result3?true:false;
														//插入心愿单																									
														$sday=date('Y-m-',time()).'1';
														$eday=date('Y-m-d',strtotime("$sday +1 month"));
														$sday=strtotime($sday);
														$eday=strtotime($eday);
														$lastwish=$db->ig2_select("mae_wish_list","uid=".$user['id']." and create_time >= $sday and create_time < $eday");
														if(!$lastwish){
															$succes=$succes && $db->ig2_query("insert into mae_wish_list (`account_id`,`sell_id`,`uid`,`status`,`is_see`,`create_time`) values ('16621','".$id."','".$user['id']."','0','0','".time()."');")?true:false;
															$wishid=mysql_insert_id();
														}
														if($succes){
															$db->ig2_query('COMMIT');
														}else{
															$db->ig2_query('ROLLBACK');
														}
														if(++$co>=100){
															$this->sendTxt('服务器忙，请稍后再试('.$result1.'0'.$result2.'0'.$result3);
														}
													}
													$this->sendTxt('验证成功，成功获得15个积分，可在个人中心查看并兑换'.($wishid?'，并可填写<a href="http://rams.cc/m/shellexpert/wish.php?wishid='.$wishid.'">心愿单</a>':''));
												}else{
													//非活动商品
													$this->sendTxt('此商品为真，但不在活动商品之列');
												}
											}
											break;
										case '0002':
											//数码不存在
											$this->sendTxt('此代码不存在，请检查标签，确认代码是否正确，点击菜单重新验证');
											break;
										case '003':
											//数码不存在
											$this->sendTxt('此代码不存在，请检查标签，确认代码是否正确，点击菜单重新验证');
											break;
										case '102':
											//数码不存在
											$this->sendTxt('此代码不存在，请检查标签，确认代码是否正确，点击菜单重新验证');
											break;
										default:
											//ip限制，ip最大值等问题
											$this->sendTxt('查询异常');
											break;
									}
									exit;
								}
							}
							//未获得16位数字产品编码
							$this->sendTxt('错误二维码,若您想绑定店长或店员请在微信消息列表界面点右上角加号选扫一扫扫描二维码');
						}else{
							//非扫码验证
						}
						break;
					case 'SCAN':
						//扫描带参数的二维码
						$user=$db->ig2_want('mae_user','openid="'.$this->fromUsername.'"');
						if($user){
							//用户已存在
							$this->sendTxt('您已经有店铺，不能重复绑定');
						}else{
							//是店长二维码
							$shop=$db->ig2_want('mae_shop','code="'.$eventKey.'" or tid="'.$eventKey.'"');
							if($shop){
								//店铺存在
								if($shop['tid']==$eventKey){
									if($shop['is_activate']==1){
										//已激活
										$this->sendTxt('此店铺已有店长，不能重复绑定');
									}else{
										//未激活
										$activeshops=$db->ig2_select('mae_shop','is_activate=1 and city_id='.$shop['city_id']);
										$city=$db->ig2_want('mae_city','id='.$shop['city_id']);
										if(sizeof($activeshops)>=$city['limit']){
											$this->sendTxt('该城市已达到绑定上限，不能绑定新店');
										}else{
											//未达到城市上线
											$title='点击进入完成店长注册';
											$url=$url.'?type=1&tid='.$shop['tid'].'&openid='.$this->fromUsername;
											$this->sendNews($title,$des,$picurl,$url);
										}
									}
								}elseif($shop['code']==$eventKey){
									$users=$db->ig2_select('mae_role','is_delete=0 and role_type=2 and shop_id='.$shop['id']);
									if((sizeof($users))>=($shop['repairman_limit']+$shop['salesman_limit']))	$this->sendTxt('该店店员已达到上限');
									else{
										$title='点击进入完成店员注册';
										$url=$url.'?type=2&regtime='.time().'&tid='.$shop['tid'].'&openid='.$this->fromUsername;
										$des='请在15分钟内完成注册，超时需重新扫码。';
										$this->sendNews($title,$des,$picurl,$url);
									}
								}
							}else{
								//店铺不存在
								$this->sendTxt('店铺不存在');
							}
						}					
						break;
					case 'subscribe':
						$eventKey=explode('_',$eventKey);
						if($eventKey[0]=='qrscene'){
							//扫描带参数的二维码
							$eventKey=$eventKey[1];
							$user=$db->ig2_want('mae_user','openid="'.$this->fromUsername.'"');
							if($user){
								//用户已存在
								$this->sendTxt('您已经有店铺，不能重复绑定');
							}else{
								//是店长二维码
								$shop=$db->ig2_want('mae_shop','code="'.$eventKey.'" or tid="'.$eventKey.'"');
								if($shop){
									//店铺存在
									if($shop['tid']==$eventKey){
										if($shop['is_activate']==1){
											//已激活
											$this->sendTxt('此店铺已有店长，不能重复绑定');
										}else{
											//未激活
											$activeshops=$db->ig2_select('mae_shop','is_activate=1 and city_id='.$shop['city_id']);
											$city=$db->ig2_want('mae_city','id='.$shop['city_id']);
											if(sizeof($activeshops)>=$city['limit']){
												$this->sendTxt('该城市已达到绑定上限，不能绑定新店');
											}else{
												//未达到城市上线
												$title='点击进入完成店长注册';
												$url=$url.'?type=1&tid='.$shop['tid'].'&openid='.$this->fromUsername;
												$this->sendNews($title,$des,$picurl,$url);
											}
										}
									}elseif($shop['code']==$eventKey){
										$users=$db->ig2_select('mae_role','is_delete=0 and role_type=2 and shop_id='.$shop['id']);
										if((sizeof($users))>=($shop['repairman_limit']+$shop['salesman_limit']))	$this->sendTxt('该店店员已达到上限');
										else{
											$title='点击进入完成店员注册';
											$url=$url.'?type=2&regtime='.time().'&tid='.$shop['tid'].'&openid='.$this->fromUsername;
											$des='请在15分钟内完成注册，超时需重新扫码。';
											$this->sendNews($title,$des,$picurl,$url);
										}
									}
								}else{
									//店铺不存在
									$this->sendTxt('店铺不存在');
								}
							}	
						}
						else
							$this->sendTxt('欢迎');
						break;
					case 'CLICK':
						switch($eventKey){
							case 'writeoil':
								$this->sendTxt('请点击左下角键盘图标输入瓶盖处序列号');
								break;
							case 'readme':
								$this->sendTxt('验证积分方法：
方法一： 您可输入油桶盖上的16位号码验证积分；
方法二： 您可扫描二维码验证积分；
 
验证积分小贴士：
若验证失败，请参考以下原因耐心检查后重新输入：
1. 是否输入了错的数码（缺少或多输入一位）；
2. 您的验证码是否已被使用；
3. 您是否输入了已失效的验证码；');
								break;
							case 'cheapcode':
								$this->sendTxt('请点击左下角键盘图标，输入滚雪球卡券序列号。');
								break;
							default:
								$this->sendTxt('');
								break;
						}
						break;
					default:
						$this->sendTxt('');
						break;
				}
			}elseif($MsgType=='text'){
				$Content=trim($postObj->Content);
				if(is_numeric($Content) && strlen($Content)==18){
					$cheap_code=$db->ig2_want('mae_cheap_code','code='.$Content);
					if($cheap_code){
						if($cheap_code['count']<=$cheap_code['get_count']){
							$this->sendTxt('此代码使用已超过规定次数，请输入新码');    
						}else{
							$value=array('get_count'=>$cheap_code['get_count']+1);
							$db->ig2_update('mae_cheap_code',$value,'id='.$cheap_code['id']);
							$user=$db->ig2_want('mae_user,mae_role','mae_role.is_delete=0 and mae_user.id=mae_role.uid and mae_user.openid="'.$this->fromUsername.'"');
							$value=array(
								'id'			=>'',
								'account_id'	=>16621,
								'cheap_id'		=>$cheap_code['id'],
								'shop_id'		=>$user['shop_id'],
								'uid'			=>$user['uid'],
								'create_time'	=>time()
							);
							$db->ig2_insert('mae_cheap_code_log',$value);
							$this->sendTxt('滚雪球优惠码验证成功，您可用此凭证在门店以折扣价购买油品。');            
						}
					}else{
						tellgoto('代码不存在','cheap_code.php');
					}
				}
				$user=$db->ig2_want('mae_user','role_type=2 and openid="'.$this->fromUsername.'"');
				if(!$user){
					//扫描人不是店员
					$this->sendTxt('只有店员可以验证');
				}
				if(is_numeric($Content) && strlen($Content)==16){
					//正常获得16位数字产品编码
					$client = new SoapClient("http://accode.zhsh.co/CcnOutService.asmx?WSDL");
					$param = array(
						'userID'=>'02LS9JJ1ZQQCBVN73K392J999293K1',
						'userPwd'=>'5A82D28LAO20K38IKMNBU28KE8DD',
						'ip'=>$this->GetIP(),
						'acCode'=>$Content,
						'language'=>'zh-cn',
						'channel'=>'21'
					);
					$p = $client->__soapCall('Get_ACCodeProductInfo',array('parameters' => $param));
					$state=$p->systemState;
					$state=substr($state,0,4);
					switch($state){
						case '1002':
							//数码存在
							$sell=$db->ig2_want('mae_sell','shell_key="'.$Content.'"');
							if($sell){
								//已售出
								$this->sendTxt('此商品已售出');
							}else{
								//未售出
								$reply=$p->reply;
								$reply = simplexml_load_string($reply, 'SimpleXMLElement', LIBXML_NOCDATA);
								if($reply->item->productid=='' && ($reply->item->productspec=='小桶(3.5L-5L)'||$reply->item->productspec=='1L-5L'||$reply->item->productspec=='4L')){
									$reply->item->productid=550000000;
								}
								$pro=$db->ig2_want('mae_pro','pro_id="'.$reply->item->productid.'"');
								$p->reply=$reply;
								$p=json_encode($p);
								if($pro){
									//是活动商品
									$co=0;
									$succes=false;
									while(!$succes){
										$succes=true;
										$id=rand(1,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9);
										//插入销售记录
										$result1=$db->ig2_query("insert into mae_sell (`id`,`account_id`,`shell_key`,`pro_id`,`productname`,`productspec`,`productinfo`,`uid`,`create_time`) values ('".$id."','16621','".$Content."','".$reply->item->productid."','".$reply->item->productname."','".$reply->item->productspec."','".$p."','".$user['id']."','".time()."');");
										$succes=$succes && $result1?true:false;
										//更新积分
										$result2=$db->ig2_query("update mae_user set score=".($user['score']+SELLSCORE)." WHERE id=".$user['id']);
										$succes=$succes && $result2?true:false;
										$role=$db->ig2_want('mae_role','is_delete=0 and uid='.$user['id']);
										$result3=$db->ig2_query("update mae_shop set sell_count=sell_count+1,now_month_count=now_month_count+1,quadratic=quadratic+".SELLSCORE." WHERE id=".$role['shop_id']);
										$succes=$succes && $result3?true:false;
										//插入心愿单																									
										$sday=date('Y-m-',time()).'1';
										$eday=date('Y-m-d',strtotime("$sday +1 month"));
										$sday=strtotime($sday);
										$eday=strtotime($eday);
										$lastwish=$db->ig2_select("mae_wish_list","uid=".$user['id']." and create_time >= $sday and create_time < $eday");
										if(!$lastwish){
											$succes=$succes && $db->ig2_query("insert into mae_wish_list (`account_id`,`sell_id`,`uid`,`status`,`is_see`,`create_time`) values ('16621','".$id."','".$user['id']."','0','0','".time()."');")?true:false;
											$wishid=mysql_insert_id();
										}
										if($succes){
											$db->ig2_query('COMMIT');
										}else{
											$db->ig2_query('ROLLBACK');
										}
										if(++$co>=100){
											$this->sendTxt('服务器忙，请稍后再试('.$result1.'0'.$result2.'0'.$result3);
										}
									}
									$this->sendTxt('验证成功，成功获得15个积分，可在个人中心查看并兑换'.($wishid?'，并可填写<a href="http://rams.cc/m/shellexpert/wish.php?wishid='.$wishid.'">心愿单</a>':''));
								}else{
									//非活动商品
									$this->sendTxt('此商品为真，但不在活动商品之列');
								}
							}
							break;
						case '0002':
							//数码不存在
							$this->sendTxt('此代码不存在，请检查标签，确认代码是否正确，点击菜单重新验证');
							break;
						case '003':
							//数码不存在
							$this->sendTxt('此代码不存在，请检查标签，确认代码是否正确，点击菜单重新验证');
							break;
						case '102':
							//数码不存在
							$this->sendTxt('此代码不存在，请检查标签，确认代码是否正确，点击菜单重新验证');
							break;
						default:
							//ip限制，ip最大值等问题
							$this->sendTxt('查询异常');
							break;
					}
					exit;
				}
				//未获得16位数字产品编码
				$this->sendTxt('错误编码');
			}
		}else {
			$this->sendTxt('未知消息');
		}
	}
	
	private function sendTxt($contentStr='') {
		$textTpl = "
			<xml>
				<ToUserName><![CDATA[%s]]></ToUserName>
				<FromUserName><![CDATA[%s]]></FromUserName>
				<CreateTime>%s</CreateTime>
				<MsgType><![CDATA[text]]></MsgType>
				<Content><![CDATA[%s]]></Content>
				<FuncFlag>0</FuncFlag>
			</xml>
		";
		$time = time();
		$resultStr = sprintf($textTpl, $this->fromUsername, $this->toUsername, $time,  $contentStr);
		echo $resultStr;
		exit;
	}
	
	private function sendNews($title='',$des='',$picurl='',$url='') {
		$textTpl = "
			<xml>
				<ToUserName><![CDATA[%s]]></ToUserName>
				<FromUserName><![CDATA[%s]]></FromUserName>
				<CreateTime>%s</CreateTime>
				<MsgType><![CDATA[news]]></MsgType>
				<ArticleCount>1</ArticleCount>
				<Articles>
					<item>
						<Title><![CDATA[%s]]></Title> 
						<Description><![CDATA[%s]]></Description>
						<PicUrl><![CDATA[%s]]></PicUrl>
						<Url><![CDATA[%s]]></Url>
					</item>
				</Articles>
			</xml> 
		";	
		$time = time();
		$resultStr = sprintf($textTpl, $this->fromUsername, $this->toUsername, $time, $title, $des,$picurl,$url);
		echo $resultStr;
		exit;
	}
	private function GetIP(){
		if(!empty($_SERVER["HTTP_CLIENT_IP"])){
		  $cip = $_SERVER["HTTP_CLIENT_IP"];
		}
		elseif(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])){
		  $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
		}
		elseif(!empty($_SERVER["REMOTE_ADDR"])){
		  $cip = $_SERVER["REMOTE_ADDR"];
		}
		else{
		  $cip = "127.0.0.1";
		}
		return $cip;
	}
	private function checkSignature() {
		// you must define TOKEN by yourself
		if (!defined("TOKEN")) {
			throw new Exception('TOKEN is not defined!');
		}
		
		$signature = $_GET["signature"];
		$timestamp = $_GET["timestamp"];
		$nonce = $_GET["nonce"];
				
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
		
		// use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}

?>